package com.imut.lagain.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 数据源配置类
 * 配置HikariCP连接池
 */
@Configuration
public class DataSourceConfig {
    private static final Logger log = LoggerFactory.getLogger(DataSourceConfig.class);

    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    
    @Value("${spring.datasource.username}")
    private String username;
    
    @Value("${spring.datasource.password}")
    private String password;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    /**
     * 配置数据源
     */
    @Bean
    @Primary
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        
        log.info("基本配置");
        config.setJdbcUrl(jdbcUrl);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driverClassName);
        
        log.info("连接池配置");
        config.setMinimumIdle(5);                    // 最小空闲连接数
        config.setMaximumPoolSize(20);               // 最大连接池大小
        config.setConnectionTimeout(30000);          // 连接超时时间（毫秒）
        config.setIdleTimeout(600000);               // 空闲超时时间（毫秒）
        config.setMaxLifetime(1800000);              // 连接最大生命周期（毫秒）
        config.setLeakDetectionThreshold(60000);     // 连接泄漏检测阈值（毫秒）
        
        log.info("性能优化配置");
        config.setConnectionTestQuery("SELECT 1");   // 连接测试查询
        config.setValidationTimeout(5000);           // 验证超时时间（毫秒）
        config.setInitializationFailTimeout(1);      // 初始化失败超时时间
        
        log.info("连接池名称");
        config.setPoolName("LAgain-HikariCP");
        
        log.info("自动提交");
        config.setAutoCommit(true);
        
        log.info("只读模式（默认false）");
        config.setReadOnly(false);
        
        log.info("事务隔离级别配置已注释");
        // config.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
        
        log.info("MySQL特定配置");
        config.addDataSourceProperty("cachePrepStmts", "true");           // 缓存预编译语句
        config.addDataSourceProperty("prepStmtCacheSize", "250");         // 预编译语句缓存大小
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");    // 预编译语句SQL长度限制
        config.addDataSourceProperty("useServerPrepStmts", "true");       // 使用服务器端预编译语句
        config.addDataSourceProperty("useLocalSessionState", "true");     // 使用本地会话状态
        config.addDataSourceProperty("rewriteBatchedStatements", "true"); // 重写批量语句
        config.addDataSourceProperty("cacheResultSetMetadata", "true");   // 缓存结果集元数据
        config.addDataSourceProperty("cacheServerConfiguration", "true"); // 缓存服务器配置
        config.addDataSourceProperty("elideSetAutoCommits", "true");      // 省略自动提交设置
        config.addDataSourceProperty("maintainTimeStats", "false");       // 维护时间统计
        
        log.info("字符编码配置");
        config.addDataSourceProperty("useUnicode", "true");
        config.addDataSourceProperty("characterEncoding", "utf8");
        config.addDataSourceProperty("connectionCollation", "utf8_unicode_ci");
        
        log.info("SSL配置");
        config.addDataSourceProperty("useSSL", "false");
        config.addDataSourceProperty("allowPublicKeyRetrieval", "true");
        
        log.info("时区配置");
        config.addDataSourceProperty("serverTimezone", "Asia/Shanghai");
        
        log.info("连接初始化SQL");
        config.setConnectionInitSql("SET NAMES utf8 COLLATE utf8_unicode_ci");
        
        log.info("创建HikariDataSource");
        HikariDataSource dataSource = new HikariDataSource(config);
        
        log.info("数据源配置完成: {}", config.getPoolName());
        return dataSource;
    }
}